package cn.oracle.eshop.commondity.controller;

import cn.oracle.eshop.commondity.domain.PropertyDTO;
import cn.oracle.eshop.commondity.domain.PropertyQuery;
import cn.oracle.eshop.commondity.domain.PropertyVO;
import cn.oracle.eshop.commondity.service.PropertyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**商品属性管理模块 controller组件
 * @author wyh
 * @ClassName PropertyController
 * @date 2022/2/10 /22:34
 */
@RestController
@RequestMapping("/commodity/property")
@Slf4j
public class PropertyController {
    @Autowired
            private PropertyService propertyService;
    /***
     *分页查询商品属性
     * @author wyh
     * @date 2022/2/10
     * @param propertyQuery
     * @return java.util.List<cn.oracle.eshop.commondity.domain.PropertyVO>
    */

    List<PropertyVO> listPropertiesByPage(PropertyQuery propertyQuery){
        try {
            List<PropertyDTO> propertyDTOS= propertyService.listPropertiesByPage(propertyQuery);
            List<PropertyVO>propertyVOS=new ArrayList<>(propertyDTOS.size());
            propertyDTOS.forEach(o->propertyVOS.add(o.clone(PropertyVO.class)));
            return propertyVOS;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("error:{}",e);
        }
        return new ArrayList<PropertyVO>();
    }
    /**
     * 根据id查询商品属性
     * @param id 商品属性id
     * @return 商品属性
     */
    @GetMapping("/{id}")
    public PropertyVO getPropertyById(@PathVariable("id") Long id) {
        try {
            PropertyDTO propertyDTO = propertyService.getPropertyById(id);
            return propertyDTO.clone(PropertyVO.class);
        } catch (Exception e) {
            log.error("error:{}", e);
        }
        return new PropertyVO();
    }
    /**
     * 新增商品属性
     * @param propertyVO 商品属性VO对象
     * @return 处理结果
     */
    @PostMapping("/")
    public Boolean saveProperty(@RequestBody PropertyVO propertyVO) {
        try {
            PropertyDTO propertyDTO = propertyVO.clone(PropertyDTO.class);
            propertyService.saveProperty(propertyDTO);
        } catch (Exception e) {
            log.error("error:{}", e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 更新商品属性
     * @param propertyVO 商品属性VO对象
     * @return 处理结果
     */
    @PutMapping("/{id}")
    public Boolean updateProperty(@RequestBody PropertyVO propertyVO) {
        try {
            PropertyDTO propertyDTO = propertyVO.clone(PropertyDTO.class);
            propertyService.updateProperty(propertyDTO);
        } catch (Exception e) {
            log.error("error:{}", e.getMessage());
            return false;
        }
        return true;
    }
}
